package com.ruoyi.warehousing.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.monthlyInventory.domain.MonthlyInventory;
import com.ruoyi.monthlyInventory.domain.MonthlyInventoryLog;
import com.ruoyi.monthlyInventory.mapper.MonthlyInventoryMapper;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.sale.domain.SaleGoodsModel;
import com.ruoyi.sale.mapper.SaleGoodsMapper;
import com.ruoyi.warehousing.domain.WarehouseStatisticsVo;
import com.ruoyi.warehousing.domain.Warehousing;
import com.ruoyi.warehousing.domain.WarehousingRecords;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import com.ruoyi.warehousing.mapper.WarehousingRecordsMapper;
import com.ruoyi.warehousing.service.WarehousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WarehousingServiceImpl implements WarehousingService {

    @Autowired
    private WarehousingMapper warehousingMapper;

    @Autowired
    private WarehousingRecordsMapper warehousingRecordsMapper;

    @Autowired
    private MonthlyInventoryMapper monthlyInventoryMapper;

    @Autowired
    private SaleGoodsMapper saleGoodsMapper;

    @Autowired
    private ProductMapper productMapper;

    public static double round(double value, int places) {
        return BigDecimal.valueOf(value)
                .setScale(places, RoundingMode.HALF_UP)
                .doubleValue();
    }

    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    public List<Product> selectProductToWar(Product product) {
        product.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        return warehousingMapper.selectProductToWar(product);
    }
    @Override
    public List<WarehouseStatisticsVo> selectProductToWar_new(WarehouseStatisticsVo vo) {
        return warehousingMapper.selectProductToWar_new(vo);
    }

    public static void main(String[] args) {

        LocalDate startDate = LocalDate.of(2024, 11, 24);
        LocalDate endDate = LocalDate.of(2025, 5, 1);
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println("从 " + startDate + " 到 " + endDate + " 共有: " + daysBetween + " 天");

    }

    @Override
    public List<SaleGoodsModel> selectTendency() {
        Long deptId = SecurityUtils.getDeptId();
        Warehousing warehousing = new Warehousing();
        warehousing.setDeptId(deptId);

        List<Warehousing> warehousingList = warehousingMapper.selectWarehousingByDept(warehousing);
        List<SaleGoodsModel> saleGoodsModelList = new ArrayList<>();
        LocalDate date = LocalDate.now();
        ProductModel productModel;
        for (Warehousing warehousings : warehousingList) {

            Map<String, Object> resMap = new HashMap<>();
            resMap.put("deptId", deptId);
            resMap.put("productType", warehousings.getProductType());//
            productModel = productMapper.selectProductModelByType(resMap);

            if (productModel != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                SaleGoodsModel goodsModel = new SaleGoodsModel();
                SaleGoodsModel saleGoodsModel = new SaleGoodsModel();
                SaleGoodsModel saleGoodsModel1 = new SaleGoodsModel();
                SaleGoodsModel saleGoodsModel2 = new SaleGoodsModel();
                //  SaleGoodsModel saleGoodsModels = saleGoodsMapper.selectModelDate(productModel);
                //    if (saleGoodsModels != null) {

                saleGoodsModel1.setDeptId(deptId);
                saleGoodsModel.setBeginTime(String.valueOf(date.plusDays(-productModel.getSelectCycle())));
                Date time = null;
                try {
                    time = formatter.parse(saleGoodsModel.getBeginTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //   if (saleGoodsModels.getCreateTime().before(time)) {
                saleGoodsModel.setDeptId(deptId);
                saleGoodsModel.setEndTime(date.toString());
                saleGoodsModel2.setDeptId(deptId);
                saleGoodsModel2.setProductType(warehousings.getProductType());

                saleGoodsModel1.setBeginTime(String.valueOf(date.plusDays(-productModel.getSelectCycle()).minusYears(1)));
                saleGoodsModel1.setEndTime(String.valueOf(date.minusYears(1)));
                saleGoodsModel.setProductType(warehousings.getProductType());
                saleGoodsModel1.setProductType(warehousings.getProductType());
                SaleGoodsModel model = saleGoodsMapper.selectSaleGoodsModelTendency(saleGoodsModel);
                SaleGoodsModel model1 = saleGoodsMapper.selectSaleGoodsModelTendency(saleGoodsModel1);
                SaleGoodsModel saleGoodsModel3 = new SaleGoodsModel();

                if (model != null && model1 != null) {

                    saleGoodsModel2.setBeginTime(saleGoodsModel1.getEndTime());
                    saleGoodsModel2.setEndTime(String.valueOf(date.minusYears(1).plusDays(productModel.getPurchaseCycle())));
                    int sumNum = saleGoodsMapper.selectSumAllnum(saleGoodsModel2);
                    saleGoodsModel3.setBeginTime(String.valueOf(date.minusYears(1).plusDays(productModel.getPurchaseCycle())));
                    saleGoodsModel3.setEndTime(String.valueOf(date.minusYears(1).plusDays(productModel.getPurchaseCycle() + productModel.getPurchaseTime())));
                    saleGoodsModel3.setDeptId(deptId);
                    saleGoodsModel3.setProductType(productModel.getProductType());

                    int historySumNum = saleGoodsMapper.selectSumAllnum(saleGoodsModel3);
                    Double a = Double.valueOf(model.getAllNum());
                    Double b = Double.valueOf(model1.getAllNum());
                    goodsModel.setProductName(model.getProductName());
                    goodsModel.setProductType(model.getProductType());
                    goodsModel.setProductId(model.getProductId());
                    goodsModel.setPurchaseCycle(productModel.getPurchaseCycle());
                    goodsModel.setWarehousingNum(warehousings.getAmount());
                    goodsModel.setHistoryNum(model1.getAllNum());
                    goodsModel.setTendency(round((a - b) / b, 2));

                    goodsModel.setPurchaseUnit(productModel.getPurchaseUnit());
                    goodsModel.setExpectNum((int) (sumNum * (1 + goodsModel.getTendency())));
                    goodsModel.setPurchaseNum((int) (historySumNum * (1 + goodsModel.getTendency())));
                    goodsModel.setAllNum(model.getAllNum());
                    goodsModel.setSelectCycle(productModel.getSelectCycle());
                    goodsModel.setModelNo(productModel.getModelNo());
                    saleGoodsModelList.add(goodsModel);

                }
                  /*  } else {

                        SaleGoodsModel saleGoodsModel3 = new SaleGoodsModel();
                        LocalDate lastDay1 = YearMonth.now().minusMonths(2).atEndOfMonth();
                        LocalDate lastDay2 = YearMonth.now().minusMonths(1).atEndOfMonth();
                        SaleGoodsModel modelTime = saleGoodsMapper.selectModelTime(productModel);

                        LocalDate startDate = modelTime.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                        LocalDate nowTime = LocalDate.now();
                        long daysBetween = ChronoUnit.DAYS.between(startDate, lastDay1);
                        long dayBetween2 = ChronoUnit.DAYS.between(startDate, lastDay2);

                        saleGoodsModel2.setDeptId(deptId);
                        saleGoodsModel2.setProductType(warehousings.getProductType());
                        saleGoodsModel2.setBeginTime(startDate.toString());
                        saleGoodsModel2.setEndTime(lastDay1.toString());
                        saleGoodsModel3.setDeptId(deptId);
                        saleGoodsModel3.setProductType(warehousings.getProductType());
                        saleGoodsModel3.setBeginTime(startDate.toString());
                        saleGoodsModel3.setEndTime(lastDay2.toString());
                        SaleGoodsModel model = saleGoodsMapper.selectSaleGoodsModelTendency(saleGoodsModels);
                        int historySumNum = saleGoodsMapper.selectSumAllnum(saleGoodsModel2);

                        int sumNum = saleGoodsMapper.selectSumAllnum(saleGoodsModel3);
                        double lastDaynum = (double) historySumNum / daysBetween;
                        double lastDaynum2 = (double) sumNum / dayBetween2;
                        goodsModel.setProductName(model.getProductName());
                        goodsModel.setPurchaseCycle(productModel.getPurchaseCycle());
                        goodsModel.setWarehousingNum(warehousings.getAmount());
                        goodsModel.setTendency(Double.parseDouble(String.format("%.2f", lastDaynum / lastDaynum2)));
                        goodsModel.setExpectNum((int) (goodsModel.getTendency() * historySumNum));
                        goodsModel.setProductType(productModel.getProductType());
                        goodsModel.setPurchaseUnit(productModel.getPurchaseUnit());
                        goodsModel.setAllNum(model.getAllNum());
                        goodsModel.setSelectCycle(productModel.getSelectCycle());
                        goodsModel.setModelNo(productModel.getModelNo());
                        saleGoodsModelList.add(goodsModel);

                    }*/
            }
        }

        // }
        return saleGoodsModelList;
    }

    @Override
    public SaleGoodsModel selectCycle(SaleGoodsModel argumentModel) {
        Long deptId = SecurityUtils.getDeptId();
        Calendar calendar = Calendar.getInstance(); // 获取当前时间实例‌:ml-citation{ref="3,4" data="citationList"}
        Date nowTime = calendar.getTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        ProductModel productModel = new ProductModel();
        productModel.setDeptId(deptId);
        productModel.setModelNo(argumentModel.getModelNo());
        productModel.setSelectCycle(argumentModel.getSelectCycle());
        productModel.setProductType(argumentModel.getProductType());
        productModel.setPurchaseCycle(argumentModel.getPurchaseCycle());
        productMapper.updateProductModel(productModel);
        productModel.setPurchaseTime(30L);

        SimpleDateFormat nowTimeDate = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = nowTimeDate.format(nowTime);
        LocalDate date = LocalDate.now();
        // 2. 解析传入的日期参数
        LocalDate date1 = LocalDate.parse(nowDate, formatter);
        LocalDate previousYearDate = date1.plusDays(-argumentModel.getSelectCycle());
        SaleGoodsModel saleGoodsModel = new SaleGoodsModel();
        SaleGoodsModel saleGoodsModel1 = new SaleGoodsModel();
        saleGoodsModel.setDeptId(deptId);
        saleGoodsModel.setProductType(argumentModel.getProductType());
        saleGoodsModel.setBeginTime(String.valueOf(previousYearDate));
        saleGoodsModel.setEndTime(String.valueOf(date));
        saleGoodsModel1.setDeptId(deptId);
        saleGoodsModel1.setProductType(argumentModel.getProductType());
        saleGoodsModel1.setBeginTime(String.valueOf(previousYearDate.minusYears(1)));
        saleGoodsModel1.setEndTime(String.valueOf(date.minusYears(1)));
        SaleGoodsModel model = saleGoodsMapper.selectSaleGoodsModelTendency(saleGoodsModel);
        SaleGoodsModel model1 = saleGoodsMapper.selectSaleGoodsModelTendency(saleGoodsModel1);
        Warehousing warehousing = new Warehousing();
        warehousing.setDeptId(deptId);
        warehousing.setProductType(argumentModel.getProductType());
        SaleGoodsModel resultModel = new SaleGoodsModel();
        SaleGoodsModel saleGoodsModel2 = new SaleGoodsModel();
        SaleGoodsModel saleGoodsModel3 = new SaleGoodsModel();
        if (model != null && model1 != null) {

            saleGoodsModel2.setBeginTime(String.valueOf(date.minusYears(1)));
            saleGoodsModel2.setDeptId(deptId);
            saleGoodsModel2.setProductType(argumentModel.getProductType());
            saleGoodsModel2.setEndTime(String.valueOf(date.minusYears(1).plusDays(argumentModel.getPurchaseCycle())));
            int sumNum = saleGoodsMapper.selectSumAllnum(saleGoodsModel2);

            saleGoodsModel3.setBeginTime(String.valueOf(date.minusYears(1).plusDays(productModel.getPurchaseCycle())));
            saleGoodsModel3.setEndTime(String.valueOf(date.minusYears(1).plusDays(productModel.getPurchaseCycle() + productModel.getPurchaseTime())));
            saleGoodsModel3.setDeptId(deptId);
            saleGoodsModel3.setProductType(productModel.getProductType());

            int historySumNum = saleGoodsMapper.selectSumAllnum(saleGoodsModel3);
            Double a = Double.valueOf(model.getAllNum());
            Double b = Double.valueOf(model1.getAllNum());

            resultModel.setPurchaseCycle(productModel.getPurchaseCycle());
            resultModel.setSelectCycle(productModel.getSelectCycle());
            resultModel.setHistoryNum(model1.getAllNum());

            resultModel.setTendency(round((a - b) / b, 2));
            resultModel.setPurchaseUnit(productModel.getPurchaseUnit());
            resultModel.setExpectNum((int) Math.round(sumNum * (1 + resultModel.getTendency())));
            resultModel.setAllNum(model.getAllNum());
            resultModel.setPurchaseNum((int) (historySumNum * (1 + resultModel.getTendency())));
        }

        resultModel.setProductName(argumentModel.getProductName());
        resultModel.setModelNo(argumentModel.getModelNo());
        resultModel.setWarehousingNum(warehousingMapper.sumAllnum(warehousing));
        resultModel.setProductType(argumentModel.getProductType());
        return resultModel;

    }

    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    public List<WarehousingRecords> selectWarehousingRecords(WarehousingRecords warehousingRecords) {
        return warehousingRecordsMapper.selectWarehousingRecords(warehousingRecords);
    }

    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    public List<Warehousing> selectWarehousingDetail(Warehousing warehousing) {
        warehousing.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        return warehousingMapper.selectWarehousingDetail(warehousing);
    }

    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Warehousing> selectWarehousingDe(String keyIm) {
        Warehousing warehousing = new Warehousing();
        warehousing.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        if ("1".equals(keyIm)) {
            return warehousingMapper.selectWarehousingThree(warehousing);
        } else if ("2".equals(keyIm)) {
            return warehousingMapper.selectWarehousingSix(warehousing);
        } else if ("3".equals(keyIm)) {
            return warehousingMapper.selectWarehousingTwo(warehousing);
        } else {
            return warehousingMapper.selectWarehousingAllMonth(warehousing);
        }
    }


    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    public Warehousing selectWarehousing(Warehousing warehousing) {
        return warehousingMapper.selectWarehousing(warehousing);
    }

    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    public List<Warehousing> selectWarehousingToProduct(Warehousing warehousing) {
        warehousing.setDeptId(ShiroUtils.getSysUser().getCompanyId());
        return null;
    }

    /**
     * 查询库存预警信息
     *
     * @return 结果
     */
    @Override
    public List<Warehousing> selectWarehousingWarning() {
        Warehousing warehousing = new Warehousing();
        warehousing.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        return warehousingMapper.selectWarehousingWarning(warehousing);
    }

    /**
     * 查询库存滞销信息
     *
     * @return 结果
     */
    @Override
    public List<Warehousing> selectWarehousingMore() {
        Warehousing warehousing = new Warehousing();
        warehousing.setDeptId(ShiroUtils.getSysUser().getCompanyId());
        return warehousingMapper.selectWarehousingMore(warehousing);
    }

    /**
     * 查询库存滞销信息
     *
     * @return 结果
     */
    @Override
    public List<WarehousingRecords> selectWarehousingRecordsAll() {
        return warehousingRecordsMapper.selectWarehousingRecordsAll();
    }

    /**
     * 用于统计数据计算库存
     *
     * @param monthlyInventoryLog
     */
    @Override
    @Transactional
    public void calculation(MonthlyInventoryLog monthlyInventoryLog) {

        //创建新的存储对象，存入库存
        MonthlyInventoryLog monthlyInventoryLog1 = monthlyInventoryMapper.selectMonthlyInventoryLogById(monthlyInventoryLog.getLogId());
        MonthlyInventory monthlyInventory = monthlyInventoryMapper.selectMonthlyInventoryById(monthlyInventoryLog1.getMonthlyInventoryId());
        Warehousing warehousing = new Warehousing();
        WarehousingRecords warehousingRecords = new WarehousingRecords();
        warehousing.setBatch(monthlyInventory.getBatch());
        warehousing.setDeptId(monthlyInventory.getCompanyId());
        warehousing.setProductId(monthlyInventory.getProductId());
        warehousing.setProductType(monthlyInventory.getModelNo());
        //查询产品中库存的信息
        Warehousing warehousing1 = warehousingMapper.selectWarehousing(warehousing);
        //判断是否拥有该公司该产品该型号名称的库存记录
        if (warehousing1 == null) {
            warehousingMapper.insertWarehousing(warehousing);
        } else {
            int warehousingNum = warehousing1.getWarehousingNum();
            warehousingNum = warehousingNum + monthlyInventoryLog1.getChangeNum();
            warehousing.setWarehousingNum(warehousingNum);
            warehousing.setWarehousingId(warehousing1.getWarehousingId());
            warehousing.setUpdateBy(WXShiroUtils.getUserName());
            warehousing.setUpdateTime(DateUtils.getNowDate());
            System.out.println(warehousing);
            warehousingMapper.updateWarehousing(warehousing);
        }
        Long warehousingId = warehousing.getWarehousingId();
        warehousingRecords.setWarehousingId(warehousingId);
        warehousingRecords.setInventoryNum(monthlyInventoryLog1.getChangeNum());
        warehousingRecords.setInventoryStatus("3");
        warehousingRecords.setCreateBy(WXShiroUtils.getUserName());
        //插入产品库存记录信息
        warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);
    }


    /**
     * 查询产品信息
     *
     * @return 结果
     */
    @Override
    public int updateWarehousing(Warehousing warehousing) {
        return warehousingMapper.updateWarehousing(warehousing);
    }

    /**
     * 插入修改记录
     *
     * @return 结果
     */
    @Override
    public int insertWarehousingRecords(WarehousingRecords warehousingRecords) {
        warehousingRecords.setCreateBy(ShiroUtils.getSysUser().getUserName());
        return warehousingRecordsMapper.insertWarehousingRecords(warehousingRecords);
    }

}
